package com.aim.controller.system;

import com.aim.common.annotion.Permission;
import com.aim.common.base.AjaxResult;
import com.aim.common.constant.Syscst;
import com.aim.common.enums.BizExceptionEnum;
import com.aim.common.enums.UserStatusEnum;
import com.aim.common.exception.RequestException;
import com.aim.common.exception.ServiceException;
import com.aim.common.util.*;
import com.aim.config.shiro.ShiroKit;
import com.aim.config.shiro.UserAuthService;
import com.aim.entity.system.SysDept;
import com.aim.entity.system.SysUser;
import com.aim.service.system.SysDeptService;
import com.aim.service.system.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @AUTO 用户控制器
 * @Author AIM
 * @DATE 2019/4/23
 */
@Controller
@RequestMapping("/mgr")
public class SysUserController {

	private static String PREFIX = "system/user/";

	@Autowired
	private SysUserService userService;
	@Autowired
	private UserAuthService authService;
	@Autowired
	private SysDeptService deptService;

	/**
	 * 列表页面
	 */
	@GetMapping("")
	public String index() {
		return PREFIX + "list.html";
	}

	/**
	 * 查询管理员列表
	 */
	@PostMapping("/list")
	@Permission
	@ResponseBody
	public Object list(HttpServletRequest request) {
		Map<String, Object> params = WebUtil.getRequestMap(request);
		Object deptId = params.get("deptId");
		if (deptId.equals("0")) {
			params.remove("deptId");
		}
		// 设定当前页码，以及当前页显示的条数
		PageHelper.startPage(PageUtil.getPageNum(params), PageUtil.getPageSize(params));
		List<SysUser> list = userService.findList(params);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);
		return AjaxResult.success((int) pageInfo.getTotal(), list);
	}

	/**
	 * 添加更新页面
	 */
	@Permission
	@RequestMapping(value = {"add", "/update"})
	public String update(String id, Model model) {
		if (OftenUtil.isNotEmpty(id)) {
			SysUser sysUser = userService.get(ConverterUtils.toLong(id));
			model.addAttribute("user", sysUser);
		}
		return PREFIX + "edit.html";
	}

	/**
	 * 保存
	 */
	@PostMapping("/save")
	@ResponseBody
	public Object save(SysUser user) {
		SysUser sysUser = this.userService.get(user.getUserId());
		if (null == sysUser) {
			user.setCreateTime(new Date());
			user.setCreateUser(ShiroKit.getUser().getUserId());
			user.setStatus("ENABLE");
			String salt = ShiroKit.getRandomSalt(5);
			String password = ShiroKit.md5(user.getPassword(), salt);
			user.setPassword(password);
			user.setSalt(salt);
			this.userService.save(user);
		} else {
			BeanUtils.copyProperties(user, sysUser);
			sysUser.setUpdateTime(new Date());
			sysUser.setUpdateUser(ShiroKit.getUser().getUserId());
			this.userService.update(sysUser);
		}
		return AjaxResult.success();
	}

	/**
	 * 删除
	 *
	 * @param ids 删除ID集合
	 */
	@Permission
	@PostMapping("/del")
	@ResponseBody
	public Object del(String ids) {
		if (OftenUtil.isNotEmpty(ids)) {
			List<String> dels = ConverterUtils.list(false, ids.split(","));
			ConverterUtils.listRemove(dels, "1");
			int size = dels.size();
			if (size > 0) {
				String[] strs = dels.toArray(new String[size]);
				this.userService.batchDelete(strs);
				return AjaxResult.success();
			} else {
				return AjaxResult.error("含有不能删除用户");
			}
		} else {
			return AjaxResult.error("参数异常");
		}
	}

	/**
	 * 详情页面
	 */
	@RequestMapping("/detail")
	public String detail(Model model) {
		Long userId = ShiroKit.getUserNotNull().getUserId();
		if (OftenUtil.isNotEmpty(userId)) {
			SysUser sysUser = userService.get(userId);
			Map<String, Object> map = ConverterUtils.objectToMap(sysUser);
			SysDept sysDept = deptService.get(sysUser.getDeptId());
			map.put("deptName", sysDept.getSimpleName());
			model.addAttribute("user", map);
			return PREFIX + "info.html";
		}
		return PREFIX + "edit.html";
	}

	/**
	 * 修改密码页面
	 */
	@GetMapping("/cypher")
	public String cypher() {
		return PREFIX + "cypher.html";
	}

	/**
	 * 修改密码
	 *
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 */
	@RequestMapping("/changePwd")
	@ResponseBody
	public Object changePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
		if (OftenUtil.isEmpty(oldPassword, newPassword)) {
			throw new RequestException();
		}
		this.userService.changePwd(oldPassword, newPassword);
		return AjaxResult.success();
	}

	/**
	 * 重置用户的密码
	 */
	@RequestMapping("/reset")
	@Permission(Syscst.ADMIN_NAME)
	@ResponseBody
	public Object reset(@RequestParam Long userId) {
		if (OftenUtil.isEmpty(userId)) {
			throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
		}
		this.authService.assertAuth(userId);
		SysUser user = this.userService.get(userId);
		user.setSalt(ShiroKit.getRandomSalt(5));
		user.setPassword(ShiroKit.md5(Syscst.DEFAULT_PWD, user.getSalt()));
		this.userService.update(user);
		return AjaxResult.success();
	}

	/**
	 * 修改状态
	 */
	@RequestMapping("/setState")
	@ResponseBody
	public Object changeState(String userId) {
		SysUser sysUser = this.userService.get(ConverterUtils.toLong(userId));
		if (sysUser != null) {
			if (sysUser.getStatus().equals(UserStatusEnum.OK.getCode())) {
				sysUser.setStatus(UserStatusEnum.FREEZED.getCode());
			} else {
				sysUser.setStatus(UserStatusEnum.OK.getCode());
			}
			this.userService.update(sysUser);
		}
		return AjaxResult.success(sysUser.getStatus());
	}

	/**
	 * 设置角色页面
	 */
	@Permission
	@RequestMapping("/setRole")
	public String setRoleView(String id, Model model) {
		if (OftenUtil.isNotEmpty(id)) {
			SysUser sysUser = userService.get(ConverterUtils.toLong(id));
			model.addAttribute("roleId", sysUser.getRoleId());
		}
		model.addAttribute("userId", id);
		return PREFIX + "setRole.html";
	}

	/**
	 * 修改角色
	 */
	@RequestMapping("/authRole")
	@ResponseBody
	public Object changeFreeze(String userId, String roleId) {
		SysUser sysUser = this.userService.get(ConverterUtils.toLong(userId));
		if (sysUser != null) {
			sysUser.setRoleId(roleId);
			this.userService.update(sysUser);
		}
		return AjaxResult.success(sysUser.getStatus());
	}
}
